﻿#include "MainWindow.h"

#include <QDebug>
#include <QtConcurrent>

#include "./ui_MainWindow.h"
#include "TcpClient_T.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent),
      ui(new Ui::MainWindow) {
  ui->setupUi(this);
}

MainWindow::~MainWindow() {
  delete ui;
}

void MainWindow::on_btnTest0_clicked() {
  // 准备回复的消息
  QString msg{"myTest"};
  // 实例化client
  client_ = new ZTcp::TcpClient_T{this};
  // 绑定client自身的ip和端口
  // client_->bind(QHostAddress{"10.10.8.31"},18899);
  // 设置读取到消息时的处理函数
  client_->read([](QByteArray msg) {
    qDebug() << "client receive:" << msg;
  });

  // 连接到server
  client_->connectToHost(QHostAddress{"192.168.50.147"},9966);
  // 启动
  client_->start();
}

void MainWindow::on_btnTest1_clicked() {
  // 使用记录的client在多线程发送消息
  QtConcurrent::run([=]{
    client_->write("client hello");
  });
}

void MainWindow::on_btnTest2_clicked() {
  QByteArray data{1024*1024*100,'z'};

  while (true){
    if(!client_->isBusy()){
      client_->write(data);
    }else{
      QThread::yieldCurrentThread();
      QCoreApplication::processEvents();
    }
  }
}

void MainWindow::on_btnTest3_clicked() {
  QTcpSocket socket{};
  socket.connectToHost(QHostAddress{"192.168.50.147"}, 9966);
  static QByteArray data{1024*1024*10,'z'};
  while(true){
    socket.write(data);
    socket.waitForBytesWritten();
  }
}
